#include "../../server.hpp"

void HandleClose(Channel *pchannel){
    std::cout << "close: " << pchannel->Fd() << std::endl;
    pchannel->Remove();
    delete pchannel;
}

void HandleRead(Channel *pchannel){
    int fd = pchannel->Fd();
    char buf[1024];
    int ret = ::recv(fd, buf, 1023, 0);
    if(ret < 0) { 
        return HandleClose(pchannel);   
    }
    std::cout << buf << std::endl;
    pchannel->EnableWrite();    //收到消息就可以回复消息了,启动写,写到peer
}
void HandleWrite(Channel *pchannel){
    int fd = pchannel->Fd();
    char *msg = "hello";
    int ret = send(fd, msg, strlen(msg), 0);
    if(ret < 0){
        return HandleClose(pchannel);
    }
    pchannel->DisableWrite();
}

void HandleError(Channel *pchannel){
    return HandleClose(pchannel);
}
void HandleEvent(Channel *pchannel){
    std::cout << pchannel->Fd() << " event ready" << std::endl;
}

void Acceptor(Poller *poller, Channel *lis_channel){
    int fd = lis_channel->Fd();
    int newfd = ::accept(fd, nullptr, nullptr);
    DEBUG_LOG("accepted: %d", newfd);
    if(newfd < 0) return;
    Channel *pchannel = new Channel(poller, newfd);
    pchannel->SetReadCallback(std::bind(HandleRead, pchannel));
    pchannel->SetWriteCallback(std::bind(HandleWrite, pchannel));
    pchannel->SetEventCallback(std::bind(HandleEvent, pchannel));
    pchannel->SetErrorCallback(std::bind(HandleError, pchannel));
    pchannel->SetCloseCallback(std::bind(HandleClose, pchannel));
    pchannel->EnableRead();
}


int main(){
    Poller poller;
    Socket lis_sock;
    bool ret = lis_sock.CreateServer(8500);


    Channel channel(&poller, lis_sock.Fd());
    channel.SetReadCallback(std::bind(Acceptor, &poller, &channel));
    channel.EnableRead();
    while(true){
        std::vector<Channel*> actives;
        std::cout << "polling" << std::endl;
        poller.Poll(&actives);  //看有啥事件预备好
        for(auto &active_channel : actives){
            active_channel->HandleEvent();
        }
        sleep(1);
    }
    lis_sock.Close();
    return 0;
}